package com.cunshe.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

@Controller
public class DownloadController {

    public Logger log = LoggerFactory.getLogger(getClass());


    /**
     * 文件查看或下载
     * @param date 路径
     * @param file 路径
     * @apiNote /root/date/type/file.jpg
     * @return
     */
    @GetMapping(value = "/uploads/{date}/{file}")
    public ResponseEntity<byte[]> open2(@PathVariable("date") String date, @PathVariable("file") String file){
        ApplicationHome h = new ApplicationHome(DownloadController.class.getClass());
        File source = h.getDir().getParentFile();
        String s = new StringJoiner("/", "/", "")
                .add(source.getPath()).add("uploads").add(date)
                .toString();
        source = new File(s, file);

        if(!source.exists()){
            return ResponseEntity.notFound().build();
        }
        try {
            byte[] bytes = FileCopyUtils.copyToByteArray(source);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentLength(bytes.length);
            headers.setContentType(getMediaType(headers, file));
            headers.setCacheControl(CacheControl.maxAge(3650, TimeUnit.DAYS));
            return new ResponseEntity(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 文件查看或下载
     * @param date 路径
     * @param file 路径
     * @apiNote /root/date/type/file.jpg
     * @return
     */
    @GetMapping(value = "/uploads/dsf/{date}/{file}")
    public ResponseEntity<byte[]> open(@PathVariable("date") String date, @PathVariable("file") String file){
        System.out.println("------------------------");
        ApplicationHome h = new ApplicationHome(DownloadController.class.getClass());
        File source = h.getDir().getParentFile();
        String s = new StringJoiner("/", "/", "")
                .add(source.getPath()).add("uploads").add("dsf").add(date)
                .toString();
        source = new File(s, file);

        if(!source.exists()){
            return ResponseEntity.notFound().build();
        }
        try {
            byte[] bytes = FileCopyUtils.copyToByteArray(source);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentLength(bytes.length);
            headers.setContentType(getMediaType(headers, file));
            headers.setCacheControl(CacheControl.maxAge(3650, TimeUnit.DAYS));
            return new ResponseEntity(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private MediaType getMediaType(HttpHeaders headers, String file) throws UnsupportedEncodingException {
        String f = file.toLowerCase();
        if(f.endsWith(".png")){
            return MediaType.IMAGE_PNG;
        } else if(f.endsWith(".pdf")){
            return MediaType.APPLICATION_PDF;
        } else if(f.endsWith(".jpeg") || f.endsWith("jpg")){
            return MediaType.IMAGE_JPEG;
        } else {
            String filename = new String(new String(file).getBytes("utf-8"), "iso-8859-1");
            headers.setContentDispositionFormData("attachment", filename);
            return MediaType.APPLICATION_OCTET_STREAM;
        }
    }

}
